package com.xue.handler;

import cn.hutool.core.util.ObjectUtil;
import com.xue.domain.Info;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.lang.reflect.Method;

/**
 * @author xue
 * @create 2022-09-19 9:51
 */
@ChannelHandler.Sharable
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    /**
     * 连接开启后立刻询问所有静态点坐标信息,无论有没有暂存
     *
     * @param ctx
     * @throws Exception
     */
    /*@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        UdpConnect.sendInfo(new StaticLocationRequestInfo());
        ctx.fireChannelActive();
    }*/

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        ByteBuf content = msg.content();
        if (content.readableBytes() < 5) {
            return;
        }
        if (Info.MAGIC != content.getByte(0) | content.getShort(1) != content.readableBytes()) {
            return;
        }
        content.skipBytes(3);
        int infoByte = content.readShort();
        Class<? extends Info> infoClass = Info.getInfoClass(infoByte);
        if (ObjectUtil.isNull(infoClass)) {
            return;
        }
        // 反射调用各自的decoding方法
        Method method = infoClass.getDeclaredMethod("decoding", ByteBuf.class);
        Info info = (Info) method.invoke(infoClass.newInstance(), content);

        info.setSender(msg.sender());
        ctx.fireChannelRead(info);
    }

}
